package com.zks.nio;

import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class PlainNioServer {
    public static void main(String[] args) throws Exception{
        PlainNioServer server=new PlainNioServer();
        server.service(8034);
        System.out.println("server 启动成功");
    }

    public void service(int port) throws IOException{
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.configureBlocking(false);

            ServerSocket socket = serverSocketChannel.socket();

            InetSocketAddress address=new InetSocketAddress("localhost",port);
            socket.bind(address);
            Selector selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
           while(true){
                //等待需要处理的新事件 阻塞
                try{
                    selector.select();
                    
                }catch (Exception e){
                    e.printStackTrace();
                }

                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while(iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if(key.isAcceptable()){
                        System.out.println(" 有新的连接");
                        ServerSocketChannel channel =(ServerSocketChannel) key.channel();
                        SocketChannel client = channel.accept();
                        client.configureBlocking(false);
                        client.register(selector,SelectionKey.OP_READ);
                    }
                    if(key.isReadable()){
                       SocketChannel client=(SocketChannel) key.channel();
                        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
                        int count = client.read(byteBuffer);
                        if(count>0){
                            String receiveMessage=new String(byteBuffer.array(),CharsetUtil.UTF_8);
                            System.out.println("receive message:"+receiveMessage);

                            ByteBuffer writeBuffer=ByteBuffer.allocate(10240);
                            writeBuffer.put((receiveMessage+"abc").getBytes());
                            writeBuffer.flip();
                            client.write(writeBuffer);

                        }

                    }
                    iterator.remove();
                }

            }



        }

    }
}
